/*
 * @(#)MaintDmsClipBoardUpdateAlertAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.web;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.alert.bean.MtmUpdateAlertRecipient;
import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.alert.bean.UpdateAlertType;
import com.dcivision.alert.core.AlertManager;
import com.dcivision.alert.dao.UpdateAlertDAObject;
import com.dcivision.alert.dao.UpdateAlertTypeDAObject;
import com.dcivision.alert.web.ListUpdateAlertSummaryForm;
import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.EmailAuditTrailConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsEmailAuditTrail;
import com.dcivision.dms.bean.DmsSendEmail;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.dao.DmsEmailAuditTrailDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;

/**
  MaintDmsClipBoardUpdateAlertAction.java
  This class is for maint update alert action
    @author          Weison Liang
    @company         DCIVision Limited
    @creation date   07/12/2004
    @version         $Revision: 1.11.2.1 $
 */

public class MaintDmsClipBoardUpdateAlertAction extends com.dcivision.alert.web.MaintUpdateAlertAction {

  public static final String REVISION = "$Revision: 1.11.2.1 $";

  public static final String SEPARATOR = ",";

  public MaintDmsClipBoardUpdateAlertAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return ("com.dcivision.alert.dao.UpdateAlertDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return (null);
  }

  /**
   *  Method execute() - set request attributes and call super method
   *
   *  @param      mapping               ActionMapping from struts
   *  @param      form                  ActionForm from struts
   *  @param      request               HttpServletReuqest
   *  @param      respond               HttpServletRespond
   *  @return     ActionForward         Return the action forward object for struts
   *  @throws     ServletException      Throws ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    MaintDmsClipBoardUpdateAlertForm maintDmsClipBoardUpdateAlertForm = (MaintDmsClipBoardUpdateAlertForm) form;
    String opMode = maintDmsClipBoardUpdateAlertForm.getOpMode();
    String navMode = maintDmsClipBoardUpdateAlertForm.getNavMode();
    String docID=request.getParameter("objectID");
    String [] documentID = TextUtility.splitString(docID,",");
    request.setAttribute("objectID",docID);
    // Set function code if necessary.
    if (!Utility.isEmpty(maintDmsClipBoardUpdateAlertForm.getCurFunctionCode())) {
      this.setFunctionCode(maintDmsClipBoardUpdateAlertForm.getCurFunctionCode());
    }

    String alertType = maintDmsClipBoardUpdateAlertForm.getAlertType();
    log.debug("alertType = " + alertType);

    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);

    try {
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward != null) {
        return forward;
      }

      UpdateAlert updateAlert = null;
      UpdateAlertDAObject updateAlertDAO = new UpdateAlertDAObject(sessionContainer, conn);
      if(documentID.length>0){
        for(int i=0;i<documentID.length;i++){
          if (UpdateAlert.INVITE_TYPE.equals(maintDmsClipBoardUpdateAlertForm.getAlertType())) {
            updateAlert = (UpdateAlert) updateAlertDAO.getByObjectTypeObjectIDCreatorID(GlobalConstant.OBJECT_TYPE_DOCUMENT, TextUtility.parseIntegerObj(documentID[i])
            , sessionContainer.getUserRecordID(), UpdateAlert.INVITE_TYPE);
          } else {
            updateAlert = (UpdateAlert) updateAlertDAO.getByObjectTypeObjectIDCreatorID(GlobalConstant.OBJECT_TYPE_DOCUMENT, TextUtility.parseIntegerObj(documentID[i])
            , sessionContainer.getUserRecordID());
          }
        }
      }
          if (updateAlert != null) {
            maintDmsClipBoardUpdateAlertForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);
            maintDmsClipBoardUpdateAlertForm.setID(TextUtility.formatIntegerObj(updateAlert.getID()));
            maintDmsClipBoardUpdateAlertForm.setUpdateCount(TextUtility.formatIntegerObj(updateAlert.getUpdateCount()));
          } else {
            maintDmsClipBoardUpdateAlertForm = this.retrievalTargetObject(maintDmsClipBoardUpdateAlertForm, request);
          }
      // Retieve the root folder document object.
      DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
      String [] rootID=TextUtility.splitString(maintDmsClipBoardUpdateAlertForm.getRootID(),",");
      String nDocumentRoot="";
      if(rootID.length>0){
        for(int i=0;i<rootID.length;i++){
          DmsDocument documentRoot = docRetrievalManager.getRootFolderByRootID(TextUtility.parseIntegerObj(rootID[i]));
          nDocumentRoot=documentRoot.toString()+","+nDocumentRoot;
          request.setAttribute("rootFolder", documentRoot);
        }
      }

      sessionContainer = null;
      docRetrievalManager.release();
      updateAlertDAO = null;

      if (!Utility.isEmpty(opMode)) {
        if (GlobalConstant.OP_MODE_INSERT.equals(opMode)) {
          // Insert operation.
          try {
            this.insertRecord(mapping, maintDmsClipBoardUpdateAlertForm, request, response);
            this.handleWorkflowRoutine(mapping, maintDmsClipBoardUpdateAlertForm, request, response, opMode, navMode);
            this.commit(request);
            addMessage(request, MESSAGE_RECORD_INSERT);
            //Check to see whether need send email for enternal parties
            maintDmsClipBoardUpdateAlertForm.setObjectID(docID);
            if (DmsOperationConstant.EMAIL_SENT.equals(this.sendInvitationEmail(mapping, maintDmsClipBoardUpdateAlertForm, request, response))) {
              addMessage(request, "dms.label.email_send_successfully");
            }
          } catch (ApplicationException appEx) {
            this.rollback(request);
            handleApplicationException(request, appEx);
          }
          if (isError(request)) {
            maintDmsClipBoardUpdateAlertForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
            return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
          } else {
            maintDmsClipBoardUpdateAlertForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
            return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
          }
        } else if (GlobalConstant.OP_MODE_UPDATE.equals(opMode)) {
          // Update operation.
          try {
            this.updateRecord(mapping, maintDmsClipBoardUpdateAlertForm, request, response);
            this.handleWorkflowRoutine(mapping, maintDmsClipBoardUpdateAlertForm, request, response, opMode, navMode);
            this.commit(request);
            addMessage(request, MESSAGE_RECORD_UPDATE);
            //Check to see whether need send email for enternal parties
            maintDmsClipBoardUpdateAlertForm.setObjectID(docID);
            if (DmsOperationConstant.EMAIL_SENT.equals(this.sendInvitationEmail(mapping, maintDmsClipBoardUpdateAlertForm, request, response))) {
              addMessage(request, "dms.label.email_send_successfully");
            }
          } catch (ApplicationException appEx) {
            this.rollback(request);
            handleApplicationException(request, appEx);
          }
          if (isError(request)) {
            maintDmsClipBoardUpdateAlertForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);
            return mapping.findForward(GlobalConstant.NAV_MODE_EDIT);
          } else {
            maintDmsClipBoardUpdateAlertForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
            return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
          }
        } else if (GlobalConstant.OP_MODE_DELETE.equals(opMode)) {
          // Delete operation.
          try {
            this.deleteRecord(mapping, maintDmsClipBoardUpdateAlertForm, request, response);
            this.handleWorkflowRoutine(mapping, maintDmsClipBoardUpdateAlertForm, request, response, opMode, navMode);
            this.commit(request);
            addMessage(request, MESSAGE_RECORD_DELETE);
          } catch (ApplicationException appEx) {
            this.rollback(request);
            handleApplicationException(request, appEx);
          }
          if (isError(request)) {
            maintDmsClipBoardUpdateAlertForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);
            return mapping.findForward(GlobalConstant.NAV_MODE_EDIT);
          } else {
            maintDmsClipBoardUpdateAlertForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
            return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
          }
        } else {
          return (super.execute(mapping, form, request, response));
        }
      } else {
        return (super.execute(mapping, form, request, response));
      }
    } catch (ApplicationException appEx) {
      throw appEx;
    } finally {
      conn=null;
    }
  }

  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintDmsClipBoardUpdateAlertForm maintDmsClipBoardUpdateAlertForm = (MaintDmsClipBoardUpdateAlertForm) form;
    maintDmsClipBoardUpdateAlertForm = this.retrievalTargetObject(maintDmsClipBoardUpdateAlertForm, request);
    List typeList = new ArrayList();
    Integer inviteTypeID = null;
    log.debug("maintDmsClipBoardUpdateAlertForm.getAlertType() = " + maintDmsClipBoardUpdateAlertForm.getAlertType());
    log.debug("maintDmsClipBoardUpdateAlertForm.getID() = " + maintDmsClipBoardUpdateAlertForm.getID());

    UpdateAlert updateAlert = null;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    UpdateAlertDAObject updateAlertDAO = new UpdateAlertDAObject(sessionContainer, conn);
    String alertType="";
    if(!Utility.isEmpty(maintDmsClipBoardUpdateAlertForm.getAlertType())){
      alertType=maintDmsClipBoardUpdateAlertForm.getAlertType();
    }
    if(!Utility.isEmpty(request.getParameter("alertType"))){
      alertType=request.getParameter("alertType");
    }
    if (UpdateAlert.INVITE_TYPE.equals(alertType)) {
      updateAlert = (UpdateAlert) updateAlertDAO.getByObjectTypeObjectIDCreatorID(GlobalConstant.OBJECT_TYPE_DOCUMENT, new Integer(maintDmsClipBoardUpdateAlertForm.getObjectID())
        , sessionContainer.getUserRecordID(), UpdateAlert.INVITE_TYPE);
    } else {
      updateAlert = (UpdateAlert) updateAlertDAO.getByObjectTypeObjectIDCreatorID(GlobalConstant.OBJECT_TYPE_DOCUMENT, new Integer(maintDmsClipBoardUpdateAlertForm.getObjectID())
        , sessionContainer.getUserRecordID());
    }

    UpdateAlertTypeDAObject updateAlertTypeDAO = new UpdateAlertTypeDAObject(sessionContainer, conn);
    if (UpdateAlert.INVITE_TYPE.equals(maintDmsClipBoardUpdateAlertForm.getAlertType())) {
      typeList = updateAlertTypeDAO.getByUpdateAlertIDByOwnerID(TextUtility.parseIntegerObj(maintDmsClipBoardUpdateAlertForm.getID()), UpdateAlert.INVITE_TYPE
        , sessionContainer.getUserRecordID());
    } else {
      typeList = updateAlertTypeDAO.getByUpdateAlertIDByOwnerID(TextUtility.parseIntegerObj(maintDmsClipBoardUpdateAlertForm.getID()), sessionContainer.getUserRecordID());
    }
    // set action type
    if (!Utility.isEmpty(typeList)) {
      String[] actions = new String[typeList.size()];
      for (int i = 0; i < typeList.size(); ++i) {
        UpdateAlertType updateAlertType = (UpdateAlertType) typeList.get(i);
        actions[i] = updateAlertType.getActionType();
        if (i == 0) {
          updateAlert.setDueDate(updateAlertType.getDueDate());
          updateAlert.setMessage(updateAlertType.getMessage());
          inviteTypeID = updateAlertType.getID();
        }
      }
      maintDmsClipBoardUpdateAlertForm.setActionType(actions);
    }

    // set notify way
    if (typeList != null && typeList.size() > 0) {
      String[] asNotifyWays = TextUtility.splitString( ( (UpdateAlertType) typeList.get(0)).getNotifyWay(), this.SEPARATOR);
      maintDmsClipBoardUpdateAlertForm.setNotifyWay(asNotifyWays);
    }
    
    maintDmsClipBoardUpdateAlertForm.setFormData(updateAlert);
    maintDmsClipBoardUpdateAlertForm.setMessage(updateAlert.getMessage());

    //set Invite related info
    if (UpdateAlert.INVITE_TYPE.equals(maintDmsClipBoardUpdateAlertForm.getAlertType())) {
      AlertManager alertManager = new AlertManager(sessionContainer, conn);
      List userRecipientList = alertManager.getRecipientByUpdateAlertTypeID(inviteTypeID, UpdateAlert.USER_RECIPIENT);
      maintDmsClipBoardUpdateAlertForm.setUserList( Utility.getStringArray(userRecipientList));
      List groupRecipientList = alertManager.getRecipientByUpdateAlertTypeID(inviteTypeID, UpdateAlert.GROUP_RECIPIENT);
      maintDmsClipBoardUpdateAlertForm.setGroupList( Utility.getStringArray(groupRecipientList));
      List roleRecipientList = alertManager.getRecipientByUpdateAlertTypeID(inviteTypeID, UpdateAlert.ROLE_RECIPIENT);
      maintDmsClipBoardUpdateAlertForm.setRoleList( Utility.getStringArray(roleRecipientList));
      alertManager.release();
      if (inviteTypeID!=null){
        request.setAttribute("updateAlertTypeID", inviteTypeID.toString());
      }
    }

    sessionContainer = null;
    conn = null;
    updateAlertDAO = null;
    updateAlertTypeDAO = null;

  }

  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintDmsClipBoardUpdateAlertForm maintDmsClipBoardUpdateAlertForm = (MaintDmsClipBoardUpdateAlertForm) form;
    String docID=request.getAttribute("objectID").toString();
    String [] documentID = TextUtility.splitString(docID,",");
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
    String objectName="";
    String documentType="";
    String nObjectName="";
    String nDocumentType="";
    List attchList = new ArrayList();
    StringBuffer toAddress = new StringBuffer();
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    UpdateAlertDAObject updateAlertDAO = new UpdateAlertDAObject(sessionContainer, conn);
    UpdateAlertTypeDAObject updateAlertTypeDAO = new UpdateAlertTypeDAObject(sessionContainer, conn);
    AlertManager alertManager = new AlertManager(sessionContainer, conn);
    UpdateAlert updateAlert=new UpdateAlert();
    UpdateAlertType[] updateAlertTypes = new UpdateAlertType[documentID.length];
    // insert record into MTM_UPDATE_ALERT_RECIPIENT
    if(documentID.length>0){
        for(int i=0;i<documentID.length;i++){
            DmsDocument doc = docRetrievalManager.getDocument(TextUtility.parseIntegerObj(documentID[i]));
            if (doc != null) {
              objectName = doc.getDocumentName();
              nObjectName=objectName+","+nObjectName;
              documentType = doc.getDocumentType();
              nDocumentType=documentType+","+nDocumentType;
              updateAlert.setObjectID(TextUtility.parseIntegerObj(documentID[i]));
              updateAlert.setObjectType(GlobalConstant.OBJECT_TYPE_DOCUMENT);
              updateAlert = (UpdateAlert) updateAlertDAO.insertObject(updateAlert);
              
              String locationPath = docRetrievalManager.getLocationPath(doc.getParentID())+"\\" +doc.getDocumentName();
              attchList.add(locationPath+" ; ");
            }else{
              updateAlert = (UpdateAlert) updateAlertDAO.getByObjectTypeObjectID(GlobalConstant.OBJECT_TYPE_DOCUMENT, TextUtility.parseIntegerObj(documentID[i]));
            }
            updateAlert.setMessage(maintDmsClipBoardUpdateAlertForm.getMessage());
            updateAlert.setObjectType(GlobalConstant.OBJECT_TYPE_DOCUMENT);
            updateAlert.setDueDate(maintDmsClipBoardUpdateAlertForm.parseTimestamp(maintDmsClipBoardUpdateAlertForm.getDueDate()));
              // insert record into UPDATE_ALERT_TYPE
              String sNotify = "";
              for (int j=0; j<maintDmsClipBoardUpdateAlertForm.getNotifyWay().length; ++j) {
                sNotify += (maintDmsClipBoardUpdateAlertForm.getNotifyWay()[j] + UpdateAlert.SEPARATOR);
              }
            UpdateAlertType updateAlertType = new UpdateAlertType();
            updateAlertType.setUpdateAlertID(updateAlert.getID());
            updateAlertType.setActionType(maintDmsClipBoardUpdateAlertForm.getActionType()[0]);
            updateAlertType.setNotifyWay(sNotify);
            updateAlertType.setMessage(updateAlert.getMessage());
            updateAlertType.setDueDate(updateAlert.getDueDate());
            updateAlertType=(UpdateAlertType)updateAlertTypeDAO.insertObject(updateAlertType);
            updateAlertTypes[i]=updateAlertType;
            ListUpdateAlertSummaryForm listForm=new ListUpdateAlertSummaryForm();
            listForm.setUpdateAlertTypeID(request.getParameter("updateAlertTypeID"));
            request.setAttribute("updateAlertTypeID",request.getParameter("updateAlertTypeID"));
            maintDmsClipBoardUpdateAlertForm.setFormData(updateAlert);
            request.setAttribute("objectType", updateAlert.getObjectType());
            request.setAttribute("objectID", TextUtility.formatIntegerObj(updateAlert.getObjectID()));
            request.setAttribute("updateAlertID", TextUtility.formatIntegerObj(updateAlert.getID()));
            request.setAttribute("actionType", maintDmsClipBoardUpdateAlertForm.getAlertType());
           if (UpdateAlert.ALERT_TYPE.equals(maintDmsClipBoardUpdateAlertForm.getAlertType())) {
                // update record in DMS_DOCUMENT
                docOperationManager.setAlertEditID(TextUtility.parseIntegerObj(documentID[i]), updateAlert.getID());
              } else if (UpdateAlert.INVITE_TYPE.equals(maintDmsClipBoardUpdateAlertForm.getAlertType())) {
                // update record in DMS_DOCUMENT
                docOperationManager.setAlertInviteID(TextUtility.parseIntegerObj(documentID[i]), updateAlert.getID());
              }
      }
      MtmUpdateAlertRecipient[] updateRecipient = new MtmUpdateAlertRecipient[1];
      // insert record into MTM_UPDATE_ALERT_RECIPIENT
      // update record in DMS_DOCUMENT
      if (UpdateAlert.INVITE_TYPE.equals(maintDmsClipBoardUpdateAlertForm.getAlertType())){
        updateRecipient = alertManager.getRecipient(maintDmsClipBoardUpdateAlertForm.getUserList(), maintDmsClipBoardUpdateAlertForm.getGroupList(), maintDmsClipBoardUpdateAlertForm.getRoleList());
       
        List notifyUserIDList = alertManager.getDistinctUserIDListByLists(maintDmsClipBoardUpdateAlertForm.getUserList(), maintDmsClipBoardUpdateAlertForm.getGroupList(), maintDmsClipBoardUpdateAlertForm.getRoleList());
        for (int i = 0; i < notifyUserIDList.size(); i++) {
          //Disable the notification to creatror
          Integer userID = (Integer)notifyUserIDList.get(i);
          String userEmail = UserInfoFactory.getUserEmailAddress(userID);
          if(!Utility.isEmpty(userEmail)){
          	toAddress.append(userEmail+" ; ");
          }
        
        }
        updateAlert =alertManager.createMultiUpdateAlert(docID,nDocumentType,updateAlertTypes, updateRecipient, null, nObjectName, null, nObjectName, sessionContainer.getUserRecordID(), notifyUserIDList);
        
        // update record in DMS_DOCUMENT
     }
   }
    // add Email Audit Trail Record;
    DmsEmailAuditTrail dmsEmailAuditTrail = new DmsEmailAuditTrail();
    DmsEmailAuditTrailDAObject emailDAO = new DmsEmailAuditTrailDAObject(sessionContainer,conn);
    dmsEmailAuditTrail.setUserid(sessionContainer.getUserRecordID());
    dmsEmailAuditTrail.setOperation(EmailAuditTrailConstant.OPERATION_EXTERNAL_DOCUMENT_INVITATION);
    dmsEmailAuditTrail.setEmailType(EmailAuditTrailConstant.EMAIL_TYPE_OUTBOUND);
    dmsEmailAuditTrail.setEmailFrom(UserInfoFactory.getUserEmailAddress(sessionContainer.getUserRecordID()).toString());
    if(!Utility.isEmpty(toAddress)){
    	dmsEmailAuditTrail.setEmailTo(maintDmsClipBoardUpdateAlertForm.getRecipients().replaceAll(",",";")+";"+toAddress.toString().replaceAll(",",";"));
    }else{
    	dmsEmailAuditTrail.setEmailTo(maintDmsClipBoardUpdateAlertForm.getRecipients().replaceAll(",",";"));
    }
    dmsEmailAuditTrail.setEmailCc(maintDmsClipBoardUpdateAlertForm.getCCRecipients().replaceAll(",",";"));
    dmsEmailAuditTrail.setEmailBcc(maintDmsClipBoardUpdateAlertForm.getBCCRecipients().replaceAll(",",";"));
    dmsEmailAuditTrail.setEmailSubject(maintDmsClipBoardUpdateAlertForm.getSubject());
    dmsEmailAuditTrail.setAttchSource("DMS");
    Iterator iter = attchList.iterator();
    StringBuffer sb = new StringBuffer();
    while(iter.hasNext()){
    	String attchName = (String)iter.next();
    	sb.append(attchName);
    }
    dmsEmailAuditTrail.setAttchName(sb.toString());
    dmsEmailAuditTrail.setSentDate(Utility.getCurrentTimestamp().toString());
    dmsEmailAuditTrail.setAttchCount(new Integer(attchList.size()));
    dmsEmailAuditTrail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
	  dmsEmailAuditTrail.setCreatorID(sessionContainer.getUserRecordID());
	  dmsEmailAuditTrail.setCreateDate(Utility.getCurrentTimestamp());
	  dmsEmailAuditTrail.setUpdateCount(new Integer(0));
	  dmsEmailAuditTrail.setUpdaterID(sessionContainer.getUserRecordID());
	  dmsEmailAuditTrail.setUpdateDate(Utility.getCurrentTimestamp());
    dmsEmailAuditTrail = (DmsEmailAuditTrail)emailDAO.insertObject(dmsEmailAuditTrail);
    sessionContainer = null;
    conn = null;
    alertManager.release();
    docOperationManager.release();
  }

  public String sendInvitationEmail(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintDmsClipBoardUpdateAlertForm maintDmsClipBoardUpdateAlertForm = (MaintDmsClipBoardUpdateAlertForm) form;
    String state = "";
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    String docID=maintDmsClipBoardUpdateAlertForm.getObjectID();
    String [] documentID = TextUtility.splitString(docID,",");
    //Check for enternal parties invitation using email
    if (!Utility.isEmpty(maintDmsClipBoardUpdateAlertForm.getRecipients()) || !Utility.isEmpty(maintDmsClipBoardUpdateAlertForm.getCCRecipients()) ||
        !Utility.isEmpty(maintDmsClipBoardUpdateAlertForm.getBCCRecipients())) {
      DmsSendEmail email = new DmsSendEmail();
      email.setSender(UserInfoFactory.getUserEmailAddress(sessionContainer.getUserRecordID()));
      email.setRecipients(maintDmsClipBoardUpdateAlertForm.getRecipients());
      email.setCCRecipients(maintDmsClipBoardUpdateAlertForm.getCCRecipients());
      email.setBCCRecipients(maintDmsClipBoardUpdateAlertForm.getBCCRecipients());
      email.setSubject(maintDmsClipBoardUpdateAlertForm.getSubject());
      email.setContent(maintDmsClipBoardUpdateAlertForm.getMessage());
      String version = request.getParameter("version");
      try{
        state = docOperationManager.sendMultiDocumentByEmailAttachement(email.getSender(), email, docID, version); 
      }catch(ApplicationException appe){
        throw appe;
      }
//      if(documentID.length>0){
//        for(int i=0;i<documentID.length;i++){
//          DmsDocument document = (DmsDocument) docRetrievalManager.getDocument(TextUtility.parseIntegerObj(documentID[i]));
//          request.setAttribute("docName", document.getDocumentName());
//          String version = request.getParameter("version");
//          state = (String) docOperationManager.sendDocumentByEmailAttachement(email.getSender(), email, document, version);
//        }
//      }
    }
    sessionContainer = null;
    conn = null;
    docRetrievalManager.release();
    docOperationManager.release();
    return state;
  }

  public MaintDmsClipBoardUpdateAlertForm retrievalTargetObject(MaintDmsClipBoardUpdateAlertForm maintDmsClipBoardUpdateAlertForm, HttpServletRequest request) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    String [] documentID = TextUtility.splitString(maintDmsClipBoardUpdateAlertForm.getObjectID(),",");
    // set attribute for document
    if(documentID.length>0){
      for(int i=0;i<documentID.length;i++){
          Integer objectID = TextUtility.parseIntegerObj(documentID[i]);
          String objectName = "";
          String documentType = "";
    //DMS DOucment
          DmsDocument doc = docRetrievalManager.getDocument(objectID);
          if (doc != null) {
            objectName = doc.getDocumentName();
            documentType = doc.getDocumentType();
          }
          maintDmsClipBoardUpdateAlertForm.setObjectType(documentType);
          maintDmsClipBoardUpdateAlertForm.setObjectName(objectName);
          maintDmsClipBoardUpdateAlertForm.setObjectID(TextUtility.formatIntegerObj(objectID));
      }
    }
    sessionContainer = null;
    conn = null;
    docRetrievalManager.release();

    return maintDmsClipBoardUpdateAlertForm;
  }
  
  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
    MaintDmsClipBoardUpdateAlertForm maintDmsClipBoardUpdateAlertForm = (MaintDmsClipBoardUpdateAlertForm)form;
    String objectName = maintDmsClipBoardUpdateAlertForm.getObjectName();
    String docID=request.getAttribute("objectID").toString();
    String [] documentID = TextUtility.splitString(docID,",");
    String nDocumentType="";
    String nObjectName="";
    UpdateAlert updateAlert = null;
    List attchList = new ArrayList();
    StringBuffer toAddress = new StringBuffer();
    UpdateAlertDAObject updateAlertDAO = new UpdateAlertDAObject(sessionContainer, conn);
    UpdateAlertTypeDAObject updateAlertTypeDAO = new UpdateAlertTypeDAObject(sessionContainer, conn);
    AlertManager alertManager = new AlertManager(sessionContainer, conn);
    UpdateAlertType[] updateAlertTypes = new UpdateAlertType[documentID.length];
    String documentType = "";
    // update record in UPDATE_ALERT
    if(documentID.length>0){
        for(int i=0;i<documentID.length;i++){
            DmsDocument doc = docRetrievalManager.getDocument(TextUtility.parseIntegerObj(documentID[i]));
            if (doc != null) {
              objectName = doc.getDocumentName();
              documentType = doc.getDocumentType();
              nDocumentType=documentType+","+nDocumentType;
              nObjectName=objectName+","+nObjectName;
              
              String locationPath = docRetrievalManager.getLocationPath(doc.getParentID())+"\\" +doc.getDocumentName();
              attchList.add(locationPath+" ; ");
            }
            //if(!Utility.isEmpty(updateAlertDAO.getByObjectTypeObjectID(GlobalConstant.OBJECT_TYPE_DOCUMENT,TextUtility.parseIntegerObj(documentID[i])))){
              if (UpdateAlert.INVITE_TYPE.equals(maintDmsClipBoardUpdateAlertForm.getAlertType())) {
                updateAlert = (UpdateAlert) updateAlertDAO.getByObjectTypeObjectIDCreatorID(GlobalConstant.OBJECT_TYPE_DOCUMENT, TextUtility.parseIntegerObj(documentID[i])
                , sessionContainer.getUserRecordID(), UpdateAlert.INVITE_TYPE);
              } else {
                updateAlert = (UpdateAlert) updateAlertDAO.getByObjectTypeObjectIDCreatorID(GlobalConstant.OBJECT_TYPE_DOCUMENT, TextUtility.parseIntegerObj(documentID[i])
                , sessionContainer.getUserRecordID());
              } 
              if(updateAlert==null){
                updateAlert = new UpdateAlert();
                updateAlert.setObjectID(TextUtility.parseIntegerObj(documentID[i]));
                updateAlert.setObjectType(GlobalConstant.OBJECT_TYPE_DOCUMENT);
                updateAlert = (UpdateAlert) updateAlertDAO.insertObject(updateAlert);
                if (UpdateAlert.ALERT_TYPE.equals(maintDmsClipBoardUpdateAlertForm.getAlertType())) {
                  // update record in DMS_DOCUMENT
                  docOperationManager.setAlertEditID(TextUtility.parseIntegerObj(documentID[i]), updateAlert.getID());
                } else if (UpdateAlert.INVITE_TYPE.equals(maintDmsClipBoardUpdateAlertForm.getAlertType())) {
                  // update record in DMS_DOCUMENT
                  docOperationManager.setAlertInviteID(TextUtility.parseIntegerObj(documentID[i]), updateAlert.getID());
                }
              }
             updateAlert.setMessage(maintDmsClipBoardUpdateAlertForm.getMessage());
             updateAlert.setDueDate(maintDmsClipBoardUpdateAlertForm.parseTimestamp(maintDmsClipBoardUpdateAlertForm.getDueDate()));
             updateAlert.setAlertType(maintDmsClipBoardUpdateAlertForm.getAlertType());
             // insert record into UPDATE_ALERT_TYPE
             for (int d=0; d<maintDmsClipBoardUpdateAlertForm.getActionType().length; ++d) {
               String sNotify = "";
               for (int j=0; j<maintDmsClipBoardUpdateAlertForm.getNotifyWay().length; ++j) {
                 sNotify += (maintDmsClipBoardUpdateAlertForm.getNotifyWay()[j] + UpdateAlert.SEPARATOR);
               }
              UpdateAlertType updateAlertType = new UpdateAlertType();
              updateAlertType.setUpdateAlertID(updateAlert.getID());
              updateAlertType.setActionType(maintDmsClipBoardUpdateAlertForm.getActionType()[d]);
              updateAlertType.setNotifyWay(sNotify);
              updateAlertType.setMessage(updateAlert.getMessage());
              updateAlertType.setDueDate(updateAlert.getDueDate());
              updateAlertTypeDAO.deleteByUpdateAlertID(updateAlert.getID(),updateAlert.getAlertType());
              updateAlertType = (UpdateAlertType)updateAlertTypeDAO.insertObject(updateAlertType);
              updateAlertTypes[i]=updateAlertType;
             }
        // }
          /*else{
            this.insertRecord(mapping, maintDmsClipBoardUpdateAlertForm, request, response);
         }*/
      }
            MtmUpdateAlertRecipient[] updateRecipient = new MtmUpdateAlertRecipient[1];
           // insert record into MTM_UPDATE_ALERT_RECIPIENT
            if (UpdateAlert.INVITE_TYPE.equals(maintDmsClipBoardUpdateAlertForm.getAlertType())){
              updateRecipient = alertManager.getRecipient(maintDmsClipBoardUpdateAlertForm.getUserList(), maintDmsClipBoardUpdateAlertForm.getGroupList(), maintDmsClipBoardUpdateAlertForm.getRoleList());
              List notifyUserIDList = alertManager.getDistinctUserIDListByLists(maintDmsClipBoardUpdateAlertForm.getUserList(), maintDmsClipBoardUpdateAlertForm.getGroupList(), maintDmsClipBoardUpdateAlertForm.getRoleList());
              updateAlert =alertManager.updateMultiUpdateAlert(docID,nDocumentType,updateAlertTypes, updateRecipient, null, nObjectName, null, nObjectName, sessionContainer.getUserRecordID(), notifyUserIDList);
              for (int i = 0; i < notifyUserIDList.size(); i++) {
                //Disable the notification to creatror
                Integer userID = (Integer)notifyUserIDList.get(i);
                String userEmail = UserInfoFactory.getUserEmailAddress(userID);
                if(!Utility.isEmpty(userEmail)){
                	toAddress.append(userEmail+" ; ");
                }
              
              }
           }
           maintDmsClipBoardUpdateAlertForm.setFormData(updateAlert);
           request.setAttribute("objectType", updateAlert.getObjectType());
           request.setAttribute("objectID", TextUtility.formatIntegerObj(updateAlert.getObjectID()));
           request.setAttribute("updateAlertID", TextUtility.formatIntegerObj(updateAlert.getID()));
           request.setAttribute("actionType", maintDmsClipBoardUpdateAlertForm.getAlertType());
    }
    
    // add Email Audit Trail Record;
    DmsEmailAuditTrail dmsEmailAuditTrail = new DmsEmailAuditTrail();
    DmsEmailAuditTrailDAObject emailDAO = new DmsEmailAuditTrailDAObject(sessionContainer,conn);
    dmsEmailAuditTrail.setUserid(sessionContainer.getUserRecordID());
    dmsEmailAuditTrail.setOperation(EmailAuditTrailConstant.OPERATION_EXTERNAL_DOCUMENT_INVITATION);
    dmsEmailAuditTrail.setEmailType(EmailAuditTrailConstant.EMAIL_TYPE_OUTBOUND);
    dmsEmailAuditTrail.setEmailFrom(UserInfoFactory.getUserEmailAddress(sessionContainer.getUserRecordID()).toString());
    if(!Utility.isEmpty(toAddress)){
    	dmsEmailAuditTrail.setEmailTo(maintDmsClipBoardUpdateAlertForm.getRecipients().replaceAll(",",";")+";"+toAddress.toString().replaceAll(",",";"));
    }else{
    	dmsEmailAuditTrail.setEmailTo(maintDmsClipBoardUpdateAlertForm.getRecipients().replaceAll(",",";"));
    }
    dmsEmailAuditTrail.setEmailCc(maintDmsClipBoardUpdateAlertForm.getCCRecipients().replaceAll(",",";"));
    dmsEmailAuditTrail.setEmailBcc(maintDmsClipBoardUpdateAlertForm.getBCCRecipients().replaceAll(",",";"));
    dmsEmailAuditTrail.setEmailSubject(maintDmsClipBoardUpdateAlertForm.getSubject());
    dmsEmailAuditTrail.setAttchSource("DMS");
    Iterator iter = attchList.iterator();
    StringBuffer sb = new StringBuffer();
    while(iter.hasNext()){
    	String attchName = (String)iter.next();
    	sb.append(attchName);
    }
    dmsEmailAuditTrail.setAttchName(sb.toString());
    dmsEmailAuditTrail.setSentDate(Utility.getCurrentTimestamp().toString());
    dmsEmailAuditTrail.setAttchCount(new Integer(attchList.size()));
    dmsEmailAuditTrail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
	  dmsEmailAuditTrail.setCreatorID(sessionContainer.getUserRecordID());
	  dmsEmailAuditTrail.setCreateDate(Utility.getCurrentTimestamp());
	  dmsEmailAuditTrail.setUpdateCount(new Integer(0));
	  dmsEmailAuditTrail.setUpdaterID(sessionContainer.getUserRecordID());
	  dmsEmailAuditTrail.setUpdateDate(Utility.getCurrentTimestamp());
    dmsEmailAuditTrail = (DmsEmailAuditTrail)emailDAO.insertObject(dmsEmailAuditTrail);

    conn = null;
    sessionContainer=null;
    alertManager.release();

  }

}